/*
 * igo: com.cctv.igo.admin.scheduler.service.TaskService.java Create On 2011-5-3 下午11:22:11 By Q-Wang
 * $Revision: 1.2 $
 */
package com.ctvit.scheduler.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.ctvit.scheduler.common.SchedulerQueries;
import com.ctvit.scheduler.domain.QrtxTask;
import com.ctvit.scheduler.dto.Task;
import com.ctvit.framework.dao.Condition;
import com.ctvit.framework.dao.Pager;
import com.ctvit.framework.service.BaseService;
import com.ctvit.framework.web.context.ContextHolder;

/**
 * @author <a href="mailto:apeidou@gmail.com">Q-Wang</a>
 *
 */
public class TaskService extends BaseService {

	private Condition createCondition(QrtxTask query) {
		Condition condition = new Condition();
		if (query!=null) {
			if (StringUtils.isNotEmpty(query.getType())) {
				condition.add("type",query.getType());
			}
			if (StringUtils.isNotEmpty(query.getName())) {
				condition.add("name",query.getName());
			}
		}
		return condition;
	}

	public void save(QrtxTask task) {
		task.setCreator(ContextHolder.getCurrentUser());
		task.setCreateTimestamp(new Date());
		genericDao.insert(task);
	}

	public void update(QrtxTask task) {
		task.setModifier(ContextHolder.getCurrentUser());
		task.setModifyTimestamp(new Date());
		genericDao.updateExclusive(task, new String[]{"creator","createTimestamp"});
		// TODO Quartz 操作
	}

	public void delete(Long id, boolean cascade) {
		if (cascade) {
			genericDao.deleteBySqlID(SchedulerQueries.REMOVE_SCHEDULED_TASK_BY_TASK, id);
		}
		genericDao.removeById(QrtxTask.class, id);
		// TODO Quartz 操作
	}

	public Task get(Long id) {
		QrtxTask task = genericDao.getById(QrtxTask.class, id);
		if (task!=null) {
			return new Task(task);
		}
		return null;
	}

	public Pager<QrtxTask> list(Pager<QrtxTask> pager) {
		Condition condition = createCondition(pager.getQuery());
		List<QrtxTask> tasks = genericDao.getPagedByCondition(QrtxTask.class, condition, null, pager.getPageNo(), pager.getPageSize());
		long count = genericDao.getCountByCondition(QrtxTask.class, condition);
		pager.setResult(tasks);
		pager.setCount((int) count);
		return pager;
	}

	public List<QrtxTask> list(QrtxTask query, int pageNo, int pageSize) {
		Condition condition = createCondition(query);
		return genericDao.getByCondition(QrtxTask.class, condition, null);
	}
}
